package com.h3c.nem.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eos.common.domain.ActiveUser;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.config.SpringUtil;
import com.h3c.nem.dto.TbApprovalRecordDTO;
import com.h3c.nem.dto.TbFlowInstDTO;
import com.h3c.nem.dto.form.ConfigTheFormSubmit;
import com.h3c.nem.dto.form.GetFormBusinessData;
import com.h3c.nem.entity.SdAllWorker;
import com.h3c.nem.enums.FlowCodeEnum;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbFlowInstService;
import com.h3c.nem.utils.CommonUtil;
import com.h3c.nem.utils.ReturnCodeData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: TbFlowInstController
 *
 * @Author: l22886
 * @Date: 2022-01-19
 * Description: tb_flow_inst controller
 * Version: 1.0
 */
@Api(tags = " TbFlowInst 接口")
@Slf4j
@CrossOrigin
@RestController
@RequestMapping(value = "/tbFlowInst",produces = "application/json;charset=utf-8")
public class TbFlowInstController {

    @Resource
    private ITbFlowInstService tbFlowInstService;
    @Autowired
    CommService commService;

    /**
     * @title: queryFuzzyListForPage
     * @description: 列表分页模糊查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInstDTO", paramType = "query"),
        @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
        @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryFuzzyListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryFuzzyListForPage(@ModelAttribute TbFlowInstDTO paramsDTO,
                                                            @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                            @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页模糊查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {

            PageInfo<TbFlowInstDTO> pageInfo = tbFlowInstService.selectFuzzyByDtoPage(paramsDTO, currentPage, pageSize);

            data.put("data",pageInfo);
            data.put("msg", "列表分页模糊查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行列表分页模糊查询异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页模糊查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: queryListForPage
     * @description: 列表分页精确查询
     * @params: [ paramsDTO, currentPage, pageSize ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "列表分页查询", notes = "列表分页查询")
    @ApiImplicitParams({
    @ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInstDTO", paramType = "query"),
    @ApiImplicitParam(name = "currentPage", value = "当前页", required = true, dataType = "Integer", paramType = "query"),
    @ApiImplicitParam(name = "pageSize", value = "一页数据条数", required = true, dataType = "Integer", paramType = "query")
    })
    @RequestMapping(value = "/queryListForPage", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryListForPage(@ModelAttribute TbFlowInstDTO paramsDTO,
                                                       @RequestParam(name = "currentPage", required = true) Integer currentPage,
                                                       @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        log.info("准备执行  列表分页查询，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //分页
            Page page = PageHelper.startPage(currentPage, pageSize);
            //执行
            List<TbFlowInstDTO> resultDTOList = tbFlowInstService.selectFuzzyByDto(paramsDTO);
            PageInfo<TbFlowInstDTO> pageInfo = page.toPageInfo();
            pageInfo.setList(resultDTOList);
            data.put("data",pageInfo);
            data.put("msg", "列表分页查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行列表分页查询异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行列表分页查询完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }


    /**
     * @title: save
     * @description: 数据插入
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据插入", notes = "数据插入")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInst", paramType = "body")})
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> save(@RequestBody TbFlowInstDTO paramsDTO) {
        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbFlowInstService.insertDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据插入成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据插入 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据插入完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @ApiOperation(value = "查询某个小任务相关信息", notes = "查询某个小任务相关信息")
    @RequestMapping(value = "/queryTaskByDto", method = RequestMethod.GET)
    public ResponseEntity<JSONObject> queryTaskByDto(@ModelAttribute TbFlowInstDTO paramsDTO) {
        log.info("准备执行  查询某个小任务相关信息，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Map<String, Object> result = tbFlowInstService.queryTaskByDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "查询成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 查询某个小任务相关信息异常，异常信息为：", e);
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 查询某个小任务相关信息 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @ApiOperation(value = "任务表格提交", notes = "任务表格提交")
    @RequestMapping(value = "/taskFormSubmitWithFile", method = RequestMethod.POST)
    public Map<String, Object> taskFormSubmit(@ModelAttribute ConfigTheFormSubmit configTheFormSubmit, MultipartHttpServletRequest request) {
        log.info("执行 任务表格提交，传入的参数为" + configTheFormSubmit);
        Map<String, Object> result = new HashMap<>();
        try {
            //执行
            tbFlowInstService.taskFormSubmit(configTheFormSubmit);
            result.put("success", true);
            result.put("message", "流程处理完成");
        } catch (Exception e) {
            log.error("执行 任务表格提交，异常信息为：", e);
            result.put("success", false);
            result.put("message", "流程处理失败");
        }
        log.info("执行 任务表格提交 完成，准备返回的结果为：" + JSON.toJSONString(result));
        return result;
    }

    @ApiOperation(value = "查询小任务审核信息", notes = "查询小任务审核信息")
    @RequestMapping(value = "/getTaskInfoData", method = RequestMethod.POST)
    public Map<String, Object> getTaskInfoData(@RequestBody GetFormBusinessData getFormBusinessData) {
        log.info("执行 查询小任务审核信息，传入的参数为" + getFormBusinessData);
        Map<String, Object> result = new HashMap<>();
        try {
            //执行
            result = tbFlowInstService.getTaskInfoData(getFormBusinessData);
            result.put("success", true);
            result.put("message", "查询成功");
        } catch (Exception e) {
            log.error("执行 查询小任务审核信息，异常信息为：", e);
            result.put("success", false);
            result.put("message", "查询失败");
        }
        log.info("执行 查询某个小任务相关信息 完成，准备返回的结果为：" + JSON.toJSONString(result));
        return result;
    }

    @ApiOperation(value = "任务提交", notes = "任务提交")
    @RequestMapping(value = "/submitTask", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> submitTask(@RequestBody TbFlowInstDTO paramsDTO) {
//        MultiValueMap<String,MultipartFile> map = request.getMultiFileMap();// 为了获取文件，这个类是必须的
//        List<MultipartFile> list = map.get("fileList");// 获取到文件的列表

        log.info("准备执行 数据插入，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            String flowId = paramsDTO.getFlowId();
            String taskFinishNote = paramsDTO.getTaskFinishNote();
            Integer result = tbFlowInstService.submitTask(flowId, taskFinishNote, paramsDTO.getType());
            data.put("data",result);
            data.put("msg", "任务提交成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 任务提交 异常，异常信息为：", e);
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 任务提交完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @ApiOperation(value = "审核", notes = "审核")
    @RequestMapping(value = "/approvalTask", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> approvalTask(@RequestBody TbApprovalRecordDTO tbApprovalRecordDTO) {

        log.info("准备执行 审核，传入的参数为：" + JSONObject.toJSONString(tbApprovalRecordDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbFlowInstService.approvalTask(tbApprovalRecordDTO);
            data.put("data",result);
            data.put("msg", "提交成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 任务提交 异常，异常信息为：", e);
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 任务提交完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: update
     * @description: 数据修改
     * @params: [ paramsDTO ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据修改", notes = "数据修改")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInst", paramType = "body")})
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> update(@RequestBody TbFlowInstDTO paramsDTO) {
        log.info("准备执行 数据修改，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbFlowInstService.updateDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据修改成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据修改 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", e.toString());
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据修改完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * @title: delete
     * @description: 数据删除
     * @params: [ id ]
     * @return: org.springframework.http.ResponseEntity
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @ApiOperation(value = "数据删除", notes = "数据删除")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInst", paramType = "body")})
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> delete(@RequestBody TbFlowInstDTO paramsDTO) {
        log.info("准备执行 数据删除，传入的参数为：" + JSON.toJSONString(paramsDTO));
        JSONObject data = new JSONObject();
        try {
            //执行
            Integer result = tbFlowInstService.deleteDto(paramsDTO);
            data.put("data",result);
            data.put("msg", "数据删除成功");
            data.put("code", ReturnCodeData.SUCCESS);
        } catch (Exception e) {
            log.error("执行 数据删除 异常，异常信息为：" + JSON.toJSONString(e));
            data.put("msg", "数据删除失败");
            data.put("code", ReturnCodeData.FAIL);
        }
        log.info("执行 数据删除 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }


    /**
     * 转办
     */
    @ApiOperation(value = "转办", notes = "转办")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInst", paramType = "body")})
    @RequestMapping(value = "/transferSpecificFlowInst", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> transferSpecificFlowInst(@RequestBody List<TbFlowInstDTO> paramsDTOS) {
        log.info("准备执行 转办，传入的参数为：" + JSON.toJSONString(paramsDTOS));
        JSONObject data = new JSONObject();
        tbFlowInstService.transferSpecificFlowInst(paramsDTOS);
        data.put("msg", "转办成功");
        data.put("code", ReturnCodeData.SUCCESS);

        log.info("执行 转办 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * 流程控制
     */
    @ApiOperation(value = "流程控制", notes = "流程控制")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInst", paramType = "body")})
    @RequestMapping(value = "/controlSpecificFlowInst", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> controlSpecificFlowInst(@RequestBody List<TbFlowInstDTO> paramsDTOS) {
        log.info("准备执行 流程控制，传入的参数为：" + JSON.toJSONString(paramsDTOS));
        JSONObject data = new JSONObject();
        tbFlowInstService.controlSpecificFlowInst(paramsDTOS);
        data.put("msg", "流程控制成功");
        data.put("code", ReturnCodeData.SUCCESS);

        log.info("执行 流程控制 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * 流程终止
     */
    @ApiOperation(value = "流程终止", notes = "流程终止")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInst", paramType = "body")})
    @RequestMapping(value = "/endSpecificFlowInst", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> endSpecificFlowInst(@RequestBody List<TbFlowInstDTO> paramsDTOS) {
        log.info("准备执行 流程终止，传入的参数为：" + JSON.toJSONString(paramsDTOS));
        JSONObject data = new JSONObject();
        tbFlowInstService.endSpecificFlowInst(paramsDTOS);
        data.put("msg", "流程终止成功");
        data.put("code", ReturnCodeData.SUCCESS);

        log.info("执行 流程终止 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    /**
     * 邮催
     */
    @ApiOperation(value = "邮催", notes = "邮催")
    @ApiImplicitParams({@ApiImplicitParam(name = "paramsDTO", value = "实体参数信息", required = true, dataType = "TbFlowInst", paramType = "body")})
    @RequestMapping(value = "/mailReminder", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> mailReminder(@RequestBody List<TbFlowInstDTO> paramsDTOS) {
        log.info("准备执行 邮催，传入的参数为：" + JSON.toJSONString(paramsDTOS));
        JSONObject data = new JSONObject();
        tbFlowInstService.mailReminder(paramsDTOS);
        data.put("msg", "发送邮催成功");
        data.put("code", ReturnCodeData.SUCCESS);

        log.info("执行 邮催 完成，准备返回的结果为：" + JSON.toJSONString(data));
        return new ResponseEntity<>(data, HttpStatus.ACCEPTED);
    }

    @ApiOperation(value = "移动中台查询表单信息", notes = "移动中台查询表单信息")
    @RequestMapping(value = "/queryFormData", method = RequestMethod.POST)
    public Map<String, Object> queryFormData(@RequestBody GetFormBusinessData getFormBusinessData) {
        log.info("执行 移动中台查询表单信息，传入的参数为" + getFormBusinessData);
        Map<String, Object> result = new HashMap<>();
        try {
            //执行
            FlowCodeEnum codeEnum = FlowCodeEnum.getFormData(getFormBusinessData.getWorkFlowId());
            String clazzName = codeEnum.getClazzName();
            String methodName = codeEnum.getGetMethodName();
            Class<?> clazz = Class.forName(clazzName);
            Method method = clazz.getMethod(methodName, GetFormBusinessData.class);
            result = (Map<String, Object>) method.invoke(SpringUtil.getBean(clazz), getFormBusinessData);
            result.put("success", true);
            result.put("message", "查询成功");
        } catch (Exception e) {
            log.error("执行 移动中台查询表单信息，异常信息为：", e);
            result.put("success", false);
            result.put("message", "查询失败");
        }
        log.info("执行 移动中台查询表单信息 完成，准备返回的结果为：" + JSON.toJSONString(result));
        return result;
    }

    @ApiOperation(value = "移动中台提交表单信息", notes = "移动中台提交表单信息")
    @RequestMapping(value = "/submitFormDataWithFile", method = RequestMethod.POST)
    public Map<String, Object> submitFormData(@ModelAttribute ConfigTheFormSubmit formSubmit, MultipartHttpServletRequest request) {
        log.info("执行 移动中台提交表单信息，传入的参数为" + formSubmit);
        Map<String, Object> result = new HashMap<>();
        try {
            //执行
            String empNumber = formSubmit.getEmpNumber();
            SdAllWorker workerIdByDomain = commService.getWorkerIdByDomain(empNumber);
            CommonUtil.userHolder.set(ActiveUser.builder().userId(workerIdByDomain.getDomainAccount()).build());
            FlowCodeEnum codeEnum = FlowCodeEnum.getFormData(formSubmit.getWorkFlowId());
            String clazzName = codeEnum.getSubmitClazzName();
            String methodName = codeEnum.getSubmitMethodName();
            Class<?> clazz = Class.forName(clazzName);
            Method method = clazz.getMethod(methodName, ConfigTheFormSubmit.class);
            method.invoke(SpringUtil.getBean(clazz), formSubmit);
            result.put("success", true);
            result.put("message", "提交成功");
        } catch (Exception e) {
            log.error("执行 移动中台提交表单信息，异常信息为：", e);
            log.info("cause: " + e.getCause().getMessage());
            log.info("message: " + e.getMessage());
            result.put("success", true);
            result.put("message", e.getCause().getMessage());
        }
        log.info("执行 移动中台提交表单信息 完成，准备返回的结果为：" + JSON.toJSONString(result));
        return result;
    }

}
